import { defineStore } from 'pinia'
import { userInfoApi } from '~/api/user'
import type { UserInfo } from '~/api/model/user'

export const useUserStore = defineStore(
    'user',
    () => {
        // 用户信息状态
        const user = ref<UserInfo>({
            name: '',
            curVip: 0,
            id: 0,
            targetProgress: 0,
        })
        const isLogin = computed(() => {
            return Boolean(user.value && user.value.id)
        })
        // 初始化用户信息
        function setUser(userInfo: UserInfo) {
            user.value = userInfo
        }

        // 清除用户信息
        function clearUser() {
            user.value = {
                name: '',
                curVip: 0,
                id: 0,
                targetProgress: 0,
            }

        }

        // 从 API 获取用户信息
        async function getUserInfo(val:number) {
            try {
                const res = await userInfoApi()
                if (res) {
                    // console.log('获取用户信息:', res)
                    // setUser(res)
                    setUser({
                        // id: res.timestamp,
                        id: val,
                        curVip: 0,
                        name: res.message,
                        targetProgress: 60,
                    })
                }
            } catch (error) {
                console.error('获取用户信息失败:', error)
                clearUser()
            }
        }

        return {
            user,
            isLogin,
            setUser,
            clearUser,
            getUserInfo,
        }
    },
)